using '.each' method: how do I get the indexes of multiple ordered lists to each begin at [0]?

Posted by shecky on Stack Overflow See other posts from Stack Overflow or by shecky
Published on 2010-04-11T01:48:54Z Indexed on 2010/04/11 1:53 UTC
Read the original article Hit count: 293

Filed under:
|

I've got multiple divs, each with an ordered list (various lengths). I'm using jquery to add a class to each list item according to its index (for the purpose of columnizing portions of each list). What I have so far ...

<script type="text/javascript">

/*    Objective: columnize list items from a single ul or ol in a pre-determined number of columns
    1. get the index of each list item
    2. assign column class according to li's index
*/
$(document).ready(function() {

    $('ol li').each(function(index){
        // assign class according to li's index ... index = li number -1: 1-6 = 0-5; 7-12 = 6-11, etc.
        if ( index <= 5 )    {
            $(this).addClass('column-1');
            }
        if ( index > 5 && index < 12 )    {
            $(this).addClass('column-2');
            }
        if ( index > 11 )    {
            $(this).addClass('column-3');
            }

        // add another class to the first list item in each column
        $('ol li').filter(function(index) {
            return index != 0 && index % 6 == 0;
            }).addClass('reset');

    });    // closes li .each func
});    // closes doc.ready.func

</script>

... succeeds if there's only one list; when there are additional lists, the last column class ('column-3') is added to all remaining list items on the page. In other words, the script is presently indexing continuously through all subsequent lists/list items, rather than being re-set to [0] for each ordered list.

Can someone please show me the proper method/syntax to correct/amend this, so that the script addresses/indexes each ordered list anew?

many thanks in advance.

shecky

p.s. the markup is pretty straight-up:

<div class="tertiary">
 <h1>header</h1>
 <ol>
  <li><a href="#" title="a link">a link</a></li>
  <li><a href="#" title="a link">a link</a></li>
  <li><a href="#" title="a link">a link</a></li>
 </ol>
</div><!-- END div class="tertiary" -->

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript